package com.weilx959.spt.core.factory;

import com.weilx959.spt.core.utils.Assert;

import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;


/**
 * 单例工厂
 *
 * @author weilx
 * @since 2024-04-20
 */
public class SingletonFactory {
    private static final Map<Class<?>, Object> INSTANCES = new ConcurrentHashMap<>();

    private SingletonFactory() {}

    public static <T> T getInstance(Class<T> clazz) {
        if (!INSTANCES.containsKey(clazz)) {
            try {
                INSTANCES.put(clazz, clazz.getDeclaredConstructor().newInstance());
            } catch (Exception e) {
                Assert.error("Failed to create instance of " + clazz.getName(), e);
            }
        }
        return clazz.cast(INSTANCES.get(clazz));
    }
}
